<template>
    <form class="w-50 m-auto mt-5">
      <div class="mb-3">
        <label for="field1" class="form-label">Ваш email</label>
        <input type="email" :class="'form-control ' + get_msg_class('email')" id="field1" aria-describedby="emailHelp"
          v-model="email" />
        <div class="invalid-feedback">
          {{ get_msg("email") }}
        </div>
      </div>
      <button type="button" class="btn btn-primary" @click="sendForm()">
        Отправить письмо на почту с ссылкой на востановление
      </button>
      <vue-basic-alert :duration="500" :closeIn="5000" ref="alert" />
    </form>
  </template>
  
  <script>
  import VueBasicAlert from "vue-basic-alert";
  
  export default {
    props: {
      tokens: Object,
      user: Object,
    },
    components: {
      VueBasicAlert
    },
    data() {
      return {
        email: "",
        detail: [],
      };
    },
    methods: {
      get_msg_class(name) {
        let ans = "";
        this.detail.forEach((el) => {
          if (el.loc[1] == name) {
            ans = "is-invalid";
          }
        });
        return ans;
      },
      get_msg(name) {
        let ans = "";
        this.detail.forEach((el) => {
          if (el.loc[1] == name) {
            ans = el.msg;
          }
        });
        return ans;
      },
      sendForm() {
        this.detail = [];
        fetch(`${process.env.VUE_APP_BASE_URI}/recovery/`, {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            email: this.email,
          }),
        }).then(
          (resp) => {
            if (resp.status != 500) {
              resp.json().then(
                (body) => {
                  if (resp.ok) {
                    this.$refs.alert.showAlert(
                      "success",
                      `На почту вам выслано письмо`,
                      "Отправлено"
                    );
                  } else if (resp.status == 422) {
                    this.detail = body.detail;
                  } else {
                    this.$refs.alert.showAlert(
                      "error",
                      `${body.detail}`,
                      "Ошибка"
                    );
                  }
                },
                () => {
                  this.$refs.alert.showAlert(
                    "error",
                    "Ошибка сервера",
                    "Ошибка обработки json"
                  );
                }
              );
            } else {
              this.$refs.alert.showAlert("error", "Ошибка сервера", "500 error");
            }
          },
          (err) => {
            this.$refs.alert.showAlert(
              "error",
              "Ошибка сервера",
              err.message
            );
          }
        );
      },
    },
  };
  </script>
  
  <style></style>